package com.leetcode;

/**
 * 给定一个字符串，将字符串中的空格转换为%20
 *
 * 考察点：字符串查找和替换
 */
public class Offer05 {

    public static void main(String[] args) {
        String result = replaceStr("hell wo hs fli java", "#$%&*()");
        System.out.println(String.format("替换结果 = %s", result));
    }

    /**
     * 字符串替换
     * @param query
     *      即将替换的字符串
     * @param replace
     *      要替换成的字符
     * @return
     *      替换之后的值
     */
    public static String replaceStr(String query, String replace) {
        // TODO 计算空格的长度
        int klen = 0;
        int qlen = query.length();
        for (int i = 0; i < qlen; i++) {
            if (query.charAt(i) == ' ')
                klen++;
        }

        // TODO 新建一个数组长度为 query.length + klen * (replace.length - 1)
        // TODO 空间复杂度 = O(query.length + klen * (replace.length - 1))
        char[] chs = new char[query.length() + klen * (replace.length() - 1)];
        int j = 0, k = replace.length();

        // TODO 遍历字符数组
        // TODO 时间复杂度 = O(n)
        for (int i = 0; i < qlen; i++) {
            char tmp = query.charAt(i);

            if (query.charAt(i) == ' ') {
                for (int l = 0; l < k; l++) {
                    chs[j++] = replace.charAt(l);
                }
            }
            else {
                chs[j++] = tmp;
            }
        }
        return new String(chs);
    }
}
